var util = require('../../../utils/util.js');
var apiObject = require('../../../utils/api.js');
var app = getApp();

Page({
  data: {
    imageHost: apiObject.imageHost,
    farmList:[],
  }, 
  onShow: function () {
    var that = this;
    util.request(apiObject.api.getFarmList).then(function (res) {
      if (res.code == 200) {
        that.setData({
          farmList: res.result.farmList
        })
      } else {
        util.showModal(res.message);
      }
    })

  },
  addFarm: function () {
    var that=this
    util.showModal("扫描农场旁的二维码获取农场信息和控制权限").then(function(res){
      that.scanFarm();
    })
  },
  scanFarm: function () {
      var that=this;
      wx.scanCode({
        success: function (e) {
          try {
            console.log(JSON.parse(e.result))
            var r = JSON.parse(e.result)
            if (r.type=="farm"){
              util.request(apiObject.api.ownFarm,{farmId:r.id}).then(function(res){
                if (res.code == 200) {
                  util.showModal("添加成功").then(function(){
                    that.onShow();
                  });
                } else {
                  util.showModal(res.message);
                }
              })
            }else{
              util.showModal("请扫描正确的二维码")
            }
          } catch (e) {
            util.showModal("请扫描正确的二维码")
          }
        },
        fail:function(){
          
        }
      })
  },
  redirectToDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../detail/index?id='+id
    })
  },
  deleteFarm:function(e){
    var that= this;
    var id = e.currentTarget.dataset.id;
    util.showModal("确定要删除对该农场的监控吗?", true).then(function (res) {
      if (res.confirm) {
        util.request(apiObject.api.deleteFarm, {
          farmId: id
        }).then(function (res) {
          if (res.code == 200) {
            util.showModal("操作成功").then(function () {
              that.onLoad();
            });
          } else {
            util.showModal(res.message);
          }
        })
      }
    });
  }
})